<script setup>
import { onMounted } from 'vue'

onMounted(() => {
  const upload = document.getElementById('upload')
  const canvas = document.getElementById('canvas')
  const ctx = canvas.getContext('2d')
  const draw = document.getElementById('draw')

  let img = new Image()
  let startX, startY
  const drawMove = (event) => {
    startX = event.offsetX
    startY = event.offsetY
    console.log(draw.offsetLeft)
    console.log(draw.offsetLeft + event.movementX, draw.offsetTop + event.movementY)
    draw.style.left = draw.offsetLeft + event.movementX + 'px'
    draw.style.top = draw.offsetTop + event.movementY + 'px'
  }
  draw.addEventListener('mousedown', (event) => {
    console.log(event)
    startX = event.offsetX
    startY = event.offsetY
    draw.addEventListener('mousemove', drawMove)
  })

  draw.addEventListener('mouseup', (event) => {
    draw.removeEventListener('mousemove', drawMove)
    const cropWidth = draw.offsetWidth
    const cropHeight = draw.offsetHeight
    drawImg(draw.offsetLeft, draw.offsetTop, cropWidth, cropHeight)
  })
  upload.addEventListener('change', function (e) {
    const file = e.target.files[0]
    const reader = new FileReader()

    reader.onload = function (event) {
      img.onload = function () {
        // 设置 Canvas 尺寸与图片相同
        canvas.width = 800
        canvas.height = 800
        // 在 Canvas 上绘制图片
        ctx.drawImage(img, 0, 0)
      }
      img.src = event.target.result
    }
    reader.readAsDataURL(file)
  })
  document.getElementById('crop').addEventListener('click', function () {})
})
const drawImg = (cropX, cropY, cropWidth, cropHeight) => {
  // 创建一个新的 Canvas 用于存储裁剪后的图像
  const croppedCanvas = document.createElement('canvas')
  const croppedCtx = croppedCanvas.getContext('2d')
  croppedCanvas.width = cropWidth
  croppedCanvas.height = cropHeight

  // 将裁剪区域绘制到新的 Canvas 上
  croppedCtx.drawImage(canvas, cropX, cropY, cropWidth, cropHeight, 0, 0, cropWidth, cropHeight)
  croppedCanvas.toBlob((blob) => {
    const file = new File([blob], 'canvas-image.png', { type: 'image/png' })
    console.log(file)
  })
  // // 导出裁剪后的图像
  // const croppedImageURL = croppedCanvas.toDataURL('image/png')
  // console.log(croppedImageURL)

  // // 创建一个图像元素来显示裁剪后的结果
  // const croppedImage = new Image()
  // croppedImage.src = croppedImageURL
  // document.body.appendChild(croppedImage)
}
</script>

<template>
  <input type="file" id="upload" accept="image/*" />
  <div style="width: 800px; height: 800px; position: relative">
    <divc id="draw" class="draw"></divc>
    <canvas id="canvas"></canvas>
  </div>

  <button id="crop">Crop Image</button>
</template>
<style lang="scss" scoped>
.draw {
  position: absolute;
  width: 300px;
  height: 300px;
  z-index: 99;
  border: 2px #eee solid;
  top: 200px;
  left: 200px;
  background-color: transparent;
  cursor: move;
}
</style>
